package org.wiki.jdbc.factory;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.wiki.jdbc.dao.IUserDAO;
import org.wiki.jdbc.exception.FactoryException;

/**
 * DAO工厂类，通过配置文件创建具体DAO实现。
 * @author Wiki.M
 *
 */
public class DAOFactory {
	
	private static IUserDAO userDao = null; //用户数据访问对象
	
	private static DAOFactory instance = new DAOFactory();//数据访问对象工厂实例

	/**
	 * 私有构造方法
	 */
	private DAOFactory() {
			Properties prop = new Properties();
			//加载配置文件
			InputStream inStream = DAOFactory.class.getClassLoader()
					.getResourceAsStream("jdbc.properties");
			try {
				prop.load(inStream);
			} catch (IOException e) {
				throw new FactoryException("load the properties file error!");
			}
			//创建用户数据访问对象实例
			String userDaoClass = prop.getProperty("userDAOClass");
			Class clazz = null;
			
			try {
				clazz = Class.forName(userDaoClass);
				userDao = (IUserDAO) clazz.newInstance();
			} catch (ClassNotFoundException e) {
				throw new FactoryException("get the userDAOClass error!");
			}catch (InstantiationException e) {
				throw new FactoryException("instance the userDAOClass error!");
			} catch (IllegalAccessException e) {
				throw new FactoryException("illegal acess happend in DAOFactory!");
			}
		
	}

	/**
	 * 获取数据访问对象实例
	 * @return 返回数据访问对象实例
	 */
	public static DAOFactory getInstance() {
		return instance;
	}

	/**
	 * 获取用户数据访问对象实例
	 * @return 返回用户数据访问对象实例
	 */
	public IUserDAO getUserDao() {
		return userDao;
	}
}